﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WaterRevenueMS.WebUI.Common;
using System.ComponentModel.Composition;
using WaterRevenueMS.Core.Service.ReadMeterMS;
using WaterRevenueMS.WebUI.Extension.Filters;
using WaterRevenueMS.Domain.Common.Models;
using WaterRevenueMS.Componnent.Entities.ReadMeterMS;
using System.Linq.Expressions;
using WaterRevenueMS.WebUI.Extension.MvcHelper;
using WaterRevenueMS.Domain.ViewModels.ReadMeterMS.MeterRecord;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using System.Drawing;
using NPOI.SS.Util;

namespace WaterRevenueMS.WebUI.Controllers
{
    [Export]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class MeterRecordController : AdminController
    {
        [Import]
        private IMeterRecordService MeterRecordService { get; set; }

        [AdminLayout]
        public ActionResult Index()
        {
            var model = new MeterRecordModel();
            return View(model);
        }

        [AdminPermission(PermissionCustomMode.Ignore)]
        public ActionResult List(DataTableParameter param)
        {
            int total = MeterRecordService.MeterRecords.Count(t => t.IsDeleted == false);

            var expr = BuildSearchCriteria();

            var filterResult = MeterRecordService.MeterRecords.Where(expr).Select(t => new MeterRecordModel
            {
                id = t.Id,
                Du_SBC=t.Du_SBC,
                Yi_BZT=t.Yi_BZT,
                Kong_ZZT=t.Kong_ZZT,
                Chao_BDT=t.Chao_BDT,
                Yi_BBH=t.MeterInfo.Yi_BBH
            }).OrderBy(t => t.id).Skip(param.iDisplayStart).Take(param.iDisplayLength).ToList();

            int sortId = param.iDisplayStart + 1;

            var result = from c in filterResult
                         select new[]
                        {
                            sortId++.ToString(),
                            c.Yi_BBH.ToString(),
                            c.Du_SBC.ToString(),
                            c.Yi_BZT,
                            c.Kong_ZZT,
                            c.Chao_BDT.ToString("yyyy-MM-dd"),
                            c.id.ToString()
                        };

            return Json(new
            {
                sEcho = param.sEcho,
                iDisplayStart = param.iDisplayStart,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = result
            }, JsonRequestBehavior.AllowGet);
        }

        [AdminPermission(PermissionCustomMode.Ignore)]
        public string GenerateChargedtEXL(string idList)
        {
            string strJson = "{\"state\":\"";
            strJson = strJson + "1\",\"message\":\"成功\"}";
            //  string[] idL = idList.Split(',');
            //   FileStream fs = new FileStream(@idList, FileMode.Open);
            var model = new MeterRecordModel();
            using (FileStream fs = new FileStream(@idList, FileMode.Open))   //打开myxls.xls文件
            {
                HSSFWorkbook wk = new HSSFWorkbook(fs);   //把xls文件中的数据写入wk中
                for (int i = 0; i < wk.NumberOfSheets; i++)  //NumberOfSheets是myxls.xls中总共的表数
                {
                    ISheet sheet = wk.GetSheetAt(i);   //读取当前表数据

                    IRow rowTitle = sheet.GetRow(0);  //读取文件头
                    ICell cellT = rowTitle.GetCell(0);  //
                    if (cellT.ToString() == "表编号" && rowTitle.GetCell(1).ToString()=="本期读数" )
                    {
                        for (int j = 1; j <= sheet.LastRowNum; j++)  //LastRowNum 是当前表的总行数
                        {
                            IRow row = sheet.GetRow(j);  //读取当前行数据
                            if (row != null)
                            {
                                ICell cell = row.GetCell(0);  //
                                if (cell != null)
                                {

                                    model.Yi_BBH = cell.ToString();//仪表编号
                                    if (model.Yi_BBH == "")
                                    {
                                        break;
                                    }
                                    if (row.GetCell(1).ToString() == "")
                                    {
                                        break;
                                    }
                                    model.Du_SBC = Int32.Parse(row.GetCell(1).ToString());//本期度数
                                    model.Yi_BZT = row.GetCell(2).ToString();//仪表状态

                                    model.CustomerName = row.GetCell(3).ToString();
                                    DateTime dt = DateTime.Parse(model.CustomerName);

                                    model.Chao_BDT = dt;

                                    int rs = MeterRecordService.InsertDTFromExl(model);
                                    if (rs==0)
                                    {
                                        strJson = "{\"state\":\"" + "0\",\"message\":\"失败\"}";
                                        continue;
                                       
                                    }

                                }

                            }
                        }
                    }
                    else
                    {
                        continue;
                    }
                }
            }




            return strJson;
        }

        public string upload()
        {
            HttpFileCollectionBase files = HttpContext.Request.Files;
            for (int iFile = 0; iFile < files.Count; iFile++)
            {
                HttpPostedFileBase postedFile = files[iFile];
                string fileName = System.IO.Path.GetFileName(postedFile.FileName);
                if (fileName != null && fileName != string.Empty)
                {
                    postedFile.SaveAs(Server.MapPath("~/file/" + DateTime.Now.Ticks.ToString() + fileName));
                }
            }

            Response.Write(string.Format("<script type='text/javascript'>window.parent.ss();</script>"));
            return string.Empty;
        }

        private Expression<Func<MeterRecord, Boolean>> BuildSearchCriteria()
        {
            DynamicLambda<MeterRecord> bulider = new DynamicLambda<MeterRecord>();
            Expression<Func<MeterRecord, Boolean>> expr = null;
            if (!string.IsNullOrEmpty(Request["StartTime"]))
            {
                var data = Convert.ToDateTime(Request["StartTime"].Trim());
                Expression<Func<MeterRecord, Boolean>> tmp = t => t.Chao_BDT >= data;
                expr = bulider.BuildQueryAnd(expr, tmp);
            }
            if (!string.IsNullOrEmpty(Request["EndTime"]))
            {
                var data = Convert.ToDateTime(Request["EndTime"].Trim()).AddDays(1);
                Expression<Func<MeterRecord, Boolean>> tmp = t => t.Chao_BDT <= data;
                expr = bulider.BuildQueryAnd(expr, tmp);
            }
            
            Expression<Func<MeterRecord, Boolean>> tmpSolid = t => t.IsDeleted == false;
            expr = bulider.BuildQueryAnd(expr, tmpSolid);

            return expr;
        }

    }
}
